import SliderWithValue from "@/components/ui/SliderWithValue";
import { MaterialIcons } from "@expo/vector-icons";
import * as FileSystem from "expo-file-system";
import * as MediaLibrary from "expo-media-library";
import * as Sharing from "expo-sharing";
import React, { useState } from "react";
import {
  Alert,
  Platform,
  Share,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";

interface CanvasExporterProps {
  canvasRef: React.RefObject<any>;
  onExport?: (result: ExportResult) => void;
}

interface ExportResult {
  uri: string;
  width: number;
  height: number;
  format: 'png' | 'jpg';
}

interface ExportSettings {
  format: 'png' | 'jpg';
  quality: number;
  width: number;
  height: number;
  backgroundColor: string;
}

export const CanvasExporter: React.FC<CanvasExporterProps> = ({
  canvasRef,
  onExport,
}) => {
  const [isExporting, setIsExporting] = useState(false);
  const [exportSettings, setExportSettings] = useState<ExportSettings>({
    format: 'png',
    quality: 90,
    width: 1080,
    height: 1080,
    backgroundColor: '#FFFFFF',
  });

  // 预设尺寸
  const presetSizes = [
    { label: '原始尺寸', width: 0, height: 0 }, // 0 表示使用原始尺寸
    { label: '正方形 1:1', width: 1080, height: 1080 },
    { label: '手机壁纸 9:16', width: 1080, height: 1920 },
    { label: '横版海报 16:9', width: 1920, height: 1080 },
    { label: '微信朋友圈', width: 1200, height: 1200 },
    { label: '微博配图', width: 1080, height: 1080 },
    { label: '小红书', width: 1080, height: 1350 },
    { label: '抖音封面', width: 1080, height: 1920 },
  ];

  // 更新导出设置
  const updateExportSetting = <K extends keyof ExportSettings>(
    key: K,
    value: ExportSettings[K]
  ) => {
    setExportSettings(prev => ({ ...prev, [key]: value }));
  };

  // 选择预设尺寸
  const selectPresetSize = (preset: typeof presetSizes[0]) => {
    updateExportSetting('width', preset.width);
    updateExportSetting('height', preset.height);
  };

  // 导出画布为图片
  const exportCanvas = async (): Promise<string | null> => {
    if (!canvasRef.current) {
      Alert.alert('错误', '画布未准备好');
      return null;
    }

    try {
      setIsExporting(true);
      
      // 获取画布快照
      const snapshot = await canvasRef.current.exportCanvas();
      if (!snapshot) {
        throw new Error('无法获取画布快照');
      }

      // 这里应该根据 exportSettings 处理图片
      // 由于 React Native Skia 的限制，我们简化处理
      const result: ExportResult = {
        uri: snapshot.uri || snapshot,
        width: exportSettings.width || 1080,
        height: exportSettings.height || 1080,
        format: exportSettings.format,
      };

      if (onExport) {
        onExport(result);
      }

      return result.uri;
    } catch (error) {
      console.error('导出画布错误:', error);
      Alert.alert('导出失败', '请重试');
      return null;
    } finally {
      setIsExporting(false);
    }
  };

  // 保存到相册
  const saveToAlbum = async () => {
    try {
      // 请求相册权限
      const { status } = await MediaLibrary.requestPermissionsAsync();
      if (status !== 'granted') {
        Alert.alert('权限不足', '需要访问相册权限才能保存图片');
        return;
      }

      const uri = await exportCanvas();
      if (uri) {
        await MediaLibrary.saveToLibraryAsync(uri);
        Alert.alert('保存成功', '图片已保存到相册');
      }
    } catch (error) {
      console.error('保存到相册错误:', error);
      Alert.alert('保存失败', '请重试');
    }
  };

  // 分享图片
  const shareImage = async () => {
    try {
      const uri = await exportCanvas();
      if (uri) {
        if (Platform.OS === 'ios') {
          await Share.share({ url: uri });
        } else {
          await Sharing.shareAsync(uri);
        }
      }
    } catch (error) {
      console.error('分享错误:', error);
      Alert.alert('分享失败', '请重试');
    }
  };

  // 复制到剪贴板
  const copyToClipboard = async () => {
    try {
      const uri = await exportCanvas();
      if (uri) {
        // 在 React Native 中复制图片到剪贴板需要额外的库
        // 这里先显示提示
        Alert.alert('功能提示', '图片复制功能需要额外配置');
      }
    } catch (error) {
      console.error('复制错误:', error);
      Alert.alert('复制失败', '请重试');
    }
  };

  // 保存到文件
  const saveToFile = async () => {
    try {
      const uri = await exportCanvas();
      if (uri) {
        const filename = `canvas_${Date.now()}.${exportSettings.format}`;
        const documentsDir = FileSystem.documentDirectory;
        const fileUri = documentsDir + filename;
        
        await FileSystem.copyAsync({
          from: uri,
          to: fileUri,
        });
        
        Alert.alert('保存成功', `文件已保存为: ${filename}`);
      }
    } catch (error) {
      console.error('保存文件错误:', error);
      Alert.alert('保存失败', '请重试');
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>导出设置</Text>

      {/* 格式选择 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>导出格式</Text>
        <View style={styles.formatButtons}>
          <TouchableOpacity
            style={[
              styles.formatButton,
              exportSettings.format === 'png' && styles.formatButtonActive,
            ]}
            onPress={() => updateExportSetting('format', 'png')}
          >
            <Text
              style={[
                styles.formatButtonText,
                exportSettings.format === 'png' && styles.formatButtonTextActive,
              ]}
            >
              PNG
            </Text>
            <Text style={styles.formatDescription}>透明背景</Text>
          </TouchableOpacity>
          
          <TouchableOpacity
            style={[
              styles.formatButton,
              exportSettings.format === 'jpg' && styles.formatButtonActive,
            ]}
            onPress={() => updateExportSetting('format', 'jpg')}
          >
            <Text
              style={[
                styles.formatButtonText,
                exportSettings.format === 'jpg' && styles.formatButtonTextActive,
              ]}
            >
              JPG
            </Text>
            <Text style={styles.formatDescription}>更小文件</Text>
          </TouchableOpacity>
        </View>
      </View>

      {/* 质量设置 */}
      {exportSettings.format === 'jpg' && (
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>图片质量</Text>
          <SliderWithValue
            label="质量"
            value={exportSettings.quality}
            minimumValue={10}
            maximumValue={100}
            onValueChange={(value) => updateExportSetting('quality', value)}
            suffix="%"
          />
        </View>
      )}

      {/* 尺寸选择 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>导出尺寸</Text>
        <View style={styles.presetGrid}>
          {presetSizes.map((preset, index) => (
            <TouchableOpacity
              key={index}
              style={[
                styles.presetButton,
                exportSettings.width === preset.width &&
                exportSettings.height === preset.height &&
                styles.presetButtonActive,
              ]}
              onPress={() => selectPresetSize(preset)}
            >
              <Text style={styles.presetLabel}>{preset.label}</Text>
              {preset.width > 0 && (
                <Text style={styles.presetSize}>
                  {preset.width} × {preset.height}
                </Text>
              )}
            </TouchableOpacity>
          ))}
        </View>
      </View>

      {/* 自定义尺寸 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>自定义尺寸</Text>
        <View style={styles.customSizeContainer}>
          <SliderWithValue
            label="宽度"
            value={exportSettings.width}
            minimumValue={100}
            maximumValue={4000}
            onValueChange={(value) => updateExportSetting('width', value)}
            suffix="px"
          />
          <SliderWithValue
            label="高度"
            value={exportSettings.height}
            minimumValue={100}
            maximumValue={4000}
            onValueChange={(value) => updateExportSetting('height', value)}
            suffix="px"
          />
        </View>
      </View>

      {/* 导出操作 */}
      <View style={styles.exportActions}>
        <TouchableOpacity
          style={[styles.actionButton, styles.saveButton]}
          onPress={saveToAlbum}
          disabled={isExporting}
        >
          <MaterialIcons name="save" size={24} color="#fff" />
          <Text style={styles.actionButtonText}>保存到相册</Text>
        </TouchableOpacity>

        <TouchableOpacity
          style={[styles.actionButton, styles.shareButton]}
          onPress={shareImage}
          disabled={isExporting}
        >
          <MaterialIcons name="share" size={24} color="#fff" />
          <Text style={styles.actionButtonText}>分享</Text>
        </TouchableOpacity>

        <TouchableOpacity
          style={[styles.actionButton, styles.fileButton]}
          onPress={saveToFile}
          disabled={isExporting}
        >
          <MaterialIcons name="folder" size={24} color="#fff" />
          <Text style={styles.actionButtonText}>保存文件</Text>
        </TouchableOpacity>
      </View>

      {isExporting && (
        <View style={styles.loadingOverlay}>
          <MaterialIcons name="hourglass-empty" size={32} color="#007AFF" />
          <Text style={styles.loadingText}>正在导出...</Text>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#f5f5f5",
    maxHeight: 200
  },
  title: {
    fontSize: 20,
    fontWeight: "600",
    color: "#333",
    textAlign: "center",
    marginBottom: 25,
  },
  section: {
    backgroundColor: "#fff",
    borderRadius: 12,
    padding: 20,
    marginBottom: 15,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: "600",
    color: "#333",
    marginBottom: 15,
  },
  formatButtons: {
    flexDirection: "row",
    justifyContent: "space-around",
  },
  formatButton: {
    alignItems: "center",
    padding: 15,
    marginHorizontal: 10,
    borderRadius: 12,
    borderWidth: 2,
    borderColor: "#e0e0e0",
    backgroundColor: "#f8f8f8",
  },
  formatButtonActive: {
    borderColor: "#007AFF",
    backgroundColor: "#f0f8ff",
  },
  formatButtonText: {
    fontSize: 18,
    fontWeight: "600",
    color: "#666",
  },
  formatButtonTextActive: {
    color: "#007AFF",
  },
  formatDescription: {
    fontSize: 12,
    color: "#999",
    marginTop: 4,
  },
  presetGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "space-between",
  },
  presetButton: {
    width: "48%",
    padding: 12,
    marginBottom: 10,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: "#e0e0e0",
    backgroundColor: "#f8f8f8",
    alignItems: "center",
  },
  presetButtonActive: {
    borderColor: "#007AFF",
    backgroundColor: "#f0f8ff",
  },
  presetLabel: {
    fontSize: 14,
    fontWeight: "500",
    color: "#333",
  },
  presetSize: {
    fontSize: 12,
    color: "#666",
    marginTop: 2,
  },
  customSizeContainer: {
    marginTop: 10,
  },
  exportActions: {
    flexDirection: "row",
    justifyContent: "space-around",
    marginTop: 20,
  },
  actionButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 15,
    marginHorizontal: 5,
    borderRadius: 12,
  },
  saveButton: {
    backgroundColor: "#34C759",
  },
  shareButton: {
    backgroundColor: "#007AFF",
  },
  fileButton: {
    backgroundColor: "#FF9500",
  },
  actionButtonText: {
    color: "#fff",
    fontSize: 14,
    fontWeight: "600",
    marginLeft: 8,
  },
  loadingOverlay: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: "rgba(255,255,255,0.9)",
    alignItems: "center",
    justifyContent: "center",
  },
  loadingText: {
    marginTop: 10,
    fontSize: 16,
    color: "#007AFF",
  },
});
